<template>
    <Dialog :app-dialog="appDialog">
        <div class="gc-header">
            <ZwSearchForm
                ref="searchRef"
                row-num="3"
                :option="searchOption"
                @search="search"
                @reset="reset"
                @expand="getTableH" />
            <el-radio-group v-model="currentRow" @change="radioChange">
                <ZwTable
                    ref="tableRef"
                    class="table-box"
                    tab-h="416px"
                    row-id-key="group_id"
                    :row-key="getRowKey"
                    :echo-type="echoTypeFlag"
                    :selected-ids="echoDataId"
                    :option="tableOption"
                    :fetch-params="state.searchParams"
                    :fetch-api="fetchApi()"
                    @select-all="selectAll"
                    @selection-change="handleSelectionChange"
                    @select="selectGroup"></ZwTable>
            </el-radio-group>
        </div>
    </Dialog>

    <ZWDepart ref="DepartRef" :type="props.type" @submit="getDepart" />
</template>
<script setup lang="tsx">
import { ref, reactive, watch, nextTick, computed, h } from 'vue';
import { ElRadio, ElMessageBox } from 'element-plus';
import Dialog from '@/components/Dialog.vue';
import ZWDepart from '@/components/ZWDepart.vue';
import { getGroupManageList } from '@/api/groupManageList';
import { getSetionId } from '@/utils/utils';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import { useStore } from '@/store';
import lodash from 'lodash';
import { deepCopy } from '@/utils/helper';
import dayjs from 'dayjs';
import { cloneDeep } from 'lodash';

const store = useStore();
const tableRef: any = ref(null);
const searchRef: any = ref(null);
const emits = defineEmits(['submit', 'save']);
interface Props {
    type?: number | string | undefined;
    multiple?: boolean;
    isNotNameDisabled?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
    type: '',
    multiple: true,
    isNotNameDisabled: false
});
const DepartRef = ref(null);
const tableData = ref([]);
const selected = ref([]);
const creators = ref([]);
const single = ref(false); // 单选
const echoDataId = ref([]); //回显数据id
const echoTypeFlag = ref(false); //
const echoDataList = ref([]); // 回显数据
const formInline = reactive({
    is_qw_group: 1,
    group_leader: [],
    group_name: ''
});
const currentRow = ref<any>({});
const currentRowReal = ref<any>({});
const getRowKey = (row: any) => {
    return row.id;
};

const defaultParams = reactive({
    is_qw_group: 1,
    group_leader: [],
    group_name: ''
});
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = computed(() => {
    return [
        {
            label: '群聊名称',
            name: 'group_name',
            value: '',
            type: 'input',
            width: '280px',
            placeholder: '请输入群聊名称'
        },
        {
            label: '群主/创建人',
            name: 'group_leader',
            value: [],
            type: 'select',
            placeholder: '全部',
            multiple: true,
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});
const tableOption = computed(() => {
    const arr = [
        {
            type: 'selection',
            width: 55,
            fixed: 'left',
            reserveSelection: true
        },
        {
            prop: 'activity_name',
            label: '群名称',
            width: 200,
            render({ row }) {
                return (
                    <div style="display: flex; align-items: center">
                        <img
                            width="36"
                            height="36"
                            style="border-radius: 4px"
                            src={row.avatar ? row.avatar : '@/assets/customer/group_avatar.png'}
                            alt=""
                        />
                        <span style="margin-left: 10px; font-size: 14px; color: #33302d">{row.name}</span>
                    </div>
                );
            }
        },
        {
            prop: 'activity_name',
            label: '群主',
            width: 250,
            render({ row }) {
                return (
                    <div>
                        <div vShow={row.manager?.name}>
                            <span vShow={row.manager?.name}> {row.manager?.name}/</span>
                            <span vShow={!row.manager?.name}>-/</span>
                            {row.manager?.department_name.map((item: any) => {
                                return <span>{item.name ? item.name : '-'}</span>;
                            })}
                        </div>
                        <div vShow={!row.manager?.name}>暂无</div>
                    </div>
                );
            }
        },
        {
            prop: 'members_num',
            label: '群成员'
        },
        {
            prop: 'create_type_text',
            label: '创建方式'
        },
        {
            prop: 'create_type_text',
            label: '创建时间',
            width: 180,
            render({ row }) {
                return <span>{dayjs(row.created_at).format('YYYY-MM-DD HH:mm:ss')}</span>;
            }
        }
    ];
    const tableItem: any = {
        prop: '',
        label: '',
        width: 55,
        render({ row }) {
            return <ElRadio label={row}> &nbsp; </ElRadio>;
        }
    };
    if (single.value) {
        arr.splice(0, 1, tableItem);
    }
    return arr;
});
const fetchApi = () => {
    // 获取文件列表
    // getTableH()
    return getGroupManageList;
};
// 选中表格 checkbox
const onSelect = (selection: any) => {
    // selectId.value = getSetionId('id', selection)
};
// 全选
const onSelectAll = (selection: any) => {
    // selectId.value = getSetionId('id', selection)
};
const search = (data: any) => {
    tableRef.value.getTable().clearSelection();
    const res = { ...defaultParams, ...data };
    state.searchParams = res;
};
const reset = (v?: any) => {
    tableRef.value.getTable().clearSelection();
    const res = { ...defaultParams, ...v };
    state.searchParams = res;
};
//打开员工弹窗
const opendept = () => {
    DepartRef.value.selectedMember = creators.value;
    DepartRef.value.departVisble = true;
    DepartRef.value.title = '选择群组/创建人';
};
const getDepart = (res: any) => {
    creators.value = res;
    formInline.group_leader = getSetionId('id', creators.value);
    DepartRef.value.departVisble = false;
};
//删除选择的创建人
const changedept = (res: any) => {
    const removeDepart = creators.value.find((item: any) => !res.includes(item.id));
    creators.value = creators.value.filter((data: any) => res.includes(data.id));
    formInline.group_leader = res;
    DepartRef.value.removeItem(removeDepart);
};
// 清空查询表单
const onClear = () => {
    formInline.group_leader = [];
    formInline.group_name = '';
    creators.value = [];
    Init();
};
// 查询列表数据
const fetch = (data?: any) => {
    getGroupManageList({
        page: data?.page || 1,
        page_size: data?.page_size || 15,
        ...formInline
    }).then((res: any) => {
        tableData.value = res.data;
        if (echoDataId.value.length > 0) {
            const data: any[] = res.data.filter((item: any) => echoDataId.value.includes(item.group_id));
            nextTick(() => {
                if (single.value) {
                    currentRow.value = data[0];
                    currentRowReal.value = lodash.cloneDeep(data[0]);
                    echoDataId.value = [];
                }
            });
        } else {
            if (single.value && currentRowReal.value?.group_id) {
                currentRow.value = res.data.find(item => item.group_id == currentRowReal.value.group_id);
            }
        }
        store.dispatch('pageTotal', res.total);
    });
};
const Init = () => {
    nextTick(() => {
        fetch();
    });
};
// table 表单的全选
const selectAll = (row: any) => {
    selected.value = row;
    /**
     * 如果row为空，获取当前页面数据，将原数据在当前页的数据去掉
     * 如果row有值，判断是否在原数据里，不存在就添加进去
     */
    const list = tableRef.value.getTableData();
    if (row.length) {
        const echoList: any = [];
        row.map((el: any) => {
            if (echoDataList.value.every((item: any) => item.id != el.id)) {
                echoList.push(el);
            }
        });
        echoDataList.value = echoDataList.value.concat(echoList);
    } else {
        const echoList2: any = [];
        echoDataList.value.map((el: any) => {
            if (list.every((item: any) => item.id != el.id)) {
                echoList2.push(el);
            }
        });
        echoDataList.value = cloneDeep(echoList2);
    }
};

const handleSelectionChange = (val: any[]) => {
    selected.value = val;
};

// 选择群聊
const selectGroup = (val: any, row: any) => {
    if (single.value) {
        tableRef.value.getTable().clearSelection();
        selected.value = row;
    } else {
        selected.value = val;
        /**
         * 如果点击项row不在选中项val里，需要将点击项row从选中list里将数据去掉
         * 如果点击项row在选中项val里，需要将row放入到选中list里（本身有不需要放）
         */
        const isDel = !selected.value.some((el: any) => el.id == row.id);
        if (isDel) {
            const index = echoDataList.value.findIndex((el: any) => el.id == row.id);
            if (typeof index == 'number') {
                echoDataList.value.splice(index, 1);
            }
        } else {
            if (!echoDataList.value.some((el: any) => el.id == row.id)) {
                echoDataList.value.push(row);
            }
        }
    }
};
/**
 * 跳转企微群管理页面
 */
const toGroupManage = () => {
    const groupManagePage = location.origin + '/customer/groupManage/list';
    ElMessageBox({
        type: 'warning',
        title: '提示',
        message: h('p', null, [
            h('span', null, '须选择有名称的群聊。请在企微上修改群聊名称，并同步到'),
            h(
                'a',
                {
                    style: {
                        color: 'var(--el-color-primary)',
                        cursor: 'pointer'
                    },
                    onClick: () => window.open(groupManagePage)
                },
                '【客户中心-企微群管理】'
            ),
            h('span', null, '中，再进行选择。')
        ]),
        confirmButtonText: '我知道了'
    });
};
// 取消
const cancelHandel = () => {
    formInline.group_leader = [];
    formInline.group_name = '';
    selected.value = [];
    currentRow.value = null;
    searchRef.value.reset();
    tableRef.value.getTable().clearSelection();
    appDialog.visible = false;
};
//确定
/**
 * echoTypeFlag是true时，使用echoDataList维护回显数据
 */
const submitHandel = () => {
    if (single.value && props.isNotNameDisabled && (!currentRow.value.name || currentRow.value.name === '未设置群名')) {
        return toGroupManage();
    }
    emits('submit', single.value ? currentRow.value : echoTypeFlag.value ? echoDataList.value : selected.value);
    emits(
        'save',
        single.value
            ? mapId([currentRow.value])
            : echoTypeFlag.value
            ? mapId(echoDataList.value)
            : mapId(selected.value)
    );
    cancelHandel();
};

const mapId = arr => {
    return arr.map(item => {
        item.id = item.group_id;
        return item;
    });
};

const radioChange = () => {};

const appDialog = reactive({
    visible: false,
    title: '选择群聊',
    width: '1200px',
    append: true,
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定'
});

watch(
    () => props.multiple,
    val => {
        single.value = !val;
    }
);

const handleCurrentChange = (val: any) => {
    currentRow.value = val;
    if (!currentRowReal.value?.group_id) {
        currentRowReal.value = lodash.cloneDeep(val);
    } else if (currentRowReal.value?.group_id !== currentRow.value?.group_id) {
        currentRowReal.value = lodash.cloneDeep(val);
    }
};
defineExpose({
    appDialog,
    single,
    echoDataId,
    echoTypeFlag,
    echoDataList
});
</script>
<style scoped lang="scss">
:deep(.el-radio-group) {
    display: block !important;
}

:deep(.table_header_title) {
    height: 48px;

    th.el-table__cell {
        background: #f9f9f9;
        padding: 10px 0;
    }
}

.hide_All {
    :deep(.el-table__header-wrapper) {
        thead .table_header_title .el-checkbox {
            display: none;
        }
    }
}

.gc-header {
    margin-bottom: 20px;

    .form-inline {
        justify-content: space-between;

        .el-form-item {
            margin-bottom: 0;
            padding: 18px;
        }

        display: flex;
        align-items: center;
    }

    .btn-wrap {
        margin-right: 10px;
    }
}

.emty_img {
    margin-top: 50px;
    transform: translateX(15%);
}

.emty_title {
    margin-top: -50px;
}
</style>
